package com.chookss.home.logContacts;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.ContactEntity;
import com.chookss.home.entity.LogMembersManagerEntity;
import com.chookss.mine.personal.PersonalHomeActivity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.XJson;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LogManagerEditActivity extends BaseAct {

    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.edName)
    EditText edName;
    @BindView(R.id.edDetail)
    EditText edDetail;
    @BindView(R.id.tvLogChoiceLog)
    TextView tvLogChoiceLog;
    @BindView(R.id.tvLogChoiceDaily)
    TextView tvLogChoiceDaily;
    @BindView(R.id.tvLogChoiceWeekly)
    TextView tvLogChoiceWeekly;
    @BindView(R.id.tvLogChoiceMonthly)
    TextView tvLogChoiceMonthly;
    @BindView(R.id.llChoiceType)
    LinearLayout llChoiceType;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tvChange)
    TextView tvChange;
    @BindView(R.id.tvDelete)
    TextView tvDelete;
    @BindView(R.id.tvNum)
    TextView tvNum;
    @BindView(R.id.tvDetailInit)
    TextView tvDetailInit;
    @BindView(R.id.tvReviewer)
    TextView tvReviewer;
    @BindView(R.id.ivNameDelete)
    LinearLayout ivNameDelete;
    @BindView(R.id.llMore)
    LinearLayout llMore;
    private MyContactEntityAdapter adapter;
    private int type = 0;//默认0是编辑 1创建分组2预览分组
    private String name = "";//创建分组的默认名称
    private int choiceType = 0;
    private List<ContactEntity> contactAllList = new ArrayList<>(); //用来存放所有数据
    private List<ContactEntity> contactLittleList = new ArrayList<>(); //人数不够《=15
    private List<String> codeList = new ArrayList<>(); //新建分组的时候 存储查阅者信息的数组
    private boolean isEdit = false;//是否要编辑
    private boolean isManager = true;//是否群主
    private String id = "";//分组id
    private String teamCode = "";//团队code
    private String reportType = "3";
    private String managerCode = "", managerName = "", managerUrl = "";
    private String owerEmployeeCode = "";
    private static int SOURSE = 3;//选员工所用标识

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_log_manager_edit);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        type = getIntent().getIntExtra("type", 0);
        name = getIntent().getStringExtra("name");
        id = getIntent().getStringExtra("id");
        commonRightTxt.setTextColor(getResources().getColor(R.color.main_color));
        commonRightTxt.setText("保存");
        if (type == 0 || type == 2) {
            if (type == 0) {
                commonTitleTxt.setText("编辑分组");
                commonRightTxt.setVisibility(View.VISIBLE);
                tvDetailInit.setVisibility(View.VISIBLE);
            }
            getData();
        } else if (type == 1) {
            commonRightTxt.setVisibility(View.VISIBLE);
            tvDetailInit.setVisibility(View.VISIBLE);
            managerCode = new ShareUtils().getString(this, StaticClass.EMPLOYEECODE, "");
            managerName = new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "");
            managerUrl = new ShareUtils().getString(this, StaticClass.USER_AVATAR_URL, "");
            commonTitleTxt.setText("创建分组");
            edName.setText(name);
            setType();
            addBaseData();
        }

        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 5);
        recyclerView.setLayoutManager(gridLayoutManager1);
        adapter = new MyContactEntityAdapter(R.layout.item_log_group_manager, this, contactLittleList);
        recyclerView.setAdapter(adapter);
        recyclerView.getItemAnimator().setAddDuration(0);
        recyclerView.getItemAnimator().setChangeDuration(0);
        recyclerView.getItemAnimator().setMoveDuration(0);
        recyclerView.getItemAnimator().setRemoveDuration(0);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        edDetail.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvDetailInit.setText(s.toString().length() + "/300");
            }
        });
    }

    private void addBaseData() {
        //        type 0部门1员工
        ContactEntity contactEntity = new ContactEntity();
        contactEntity.setType("1");
        contactEntity.setHeadPhotoThumbUrl(managerUrl);
        contactEntity.setEmployeeCode(managerCode);
        contactEntity.setEmployeeName(managerName);
        contactEntity.setPost(new ShareUtils().getString(this, StaticClass.POST, ""));
        contactLittleList.add(contactEntity);
        contactAllList.add(contactEntity);
        ContactEntity contactEntity2 = new ContactEntity();
        contactEntity2.setType("2");
        contactEntity2.setEmployeeName("2");
        contactEntity2.setEmployeeCode("2");
        contactLittleList.add(contactEntity2);
        if (isManager) {
            ContactEntity contactEntity3 = new ContactEntity();
            contactEntity3.setType("3");
            contactEntity3.setEmployeeName("3");
            contactEntity3.setEmployeeCode("3");
            contactLittleList.add(contactEntity3);
            tvReviewer.setVisibility(View.VISIBLE);
        }

    }

    private void setType() {
        if (llChoiceType == null) {
            return;
        }
        for (int i = 0; i < 4; i++) {
            if (i == choiceType) {
                llChoiceType.getChildAt(i).setSelected(true);
            } else {
                llChoiceType.getChildAt(i).setSelected(false);
            }
        }
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<LogMembersManagerEntity>>() {
        }.getType(), null, Urls.selectReportTeamById, SignUtils2.makeSignStr(map), false, new ObserverCallback<LogMembersManagerEntity>() {
            @Override
            public void onSuccess(LogMembersManagerEntity data) {
                List<LogMembersManagerEntity.EmpsBean> list = data.getEmps();
                if (commonTitleTxt == null) {
                    return;
                }
                for (int i = 0; i < list.size(); i++) {
                    ContactEntity contactEntity = new ContactEntity();
                    contactEntity.setType("1");
                    contactEntity.setEmployeeName(list.get(i).getEmployeeName());
                    contactEntity.setEmployeeCode(list.get(i).getEmployeeCode());
                    contactEntity.setReviewerFlag(list.get(i).getReviewerFlag());
                    contactEntity.setPost(list.get(i).getPost());
                    if (Utils.isNull(list.get(i).getHeadPhotoThumbUrl())) {
                        contactEntity.setHeadPhotoThumbUrl(list.get(i).getHeadPhotoUrl());
                    } else {
                        contactEntity.setHeadPhotoThumbUrl(list.get(i).getHeadPhotoThumbUrl());
                    }
                    if (data.getOwerEmployeeCode().equals(list.get(i).getEmployeeCode())) {
                        if (i > 0) {
                            contactAllList.add(0, contactEntity);
                        } else {
                            contactAllList.add(contactEntity);
                        }
                        managerCode = list.get(i).getEmployeeCode();
                        managerName = list.get(i).getEmployeeName();
                        managerUrl = list.get(i).getHeadPhotoThumbUrl();
                    } else {
                        contactAllList.add(contactEntity);
                    }
                }
                reportType = data.getReportType();
                if ("3".equals(reportType)) {
                    choiceType = 0;
                } else if ("0".equals(reportType)) {
                    choiceType = 1;
                } else if ("1".equals(reportType)) {
                    choiceType = 2;
                } else if ("2".equals(reportType)) {
                    choiceType = 3;
                }
                edName.setText(data.getTeamName());
                if (type == 2) {
                    commonTitleTxt.setText(data.getTeamName());
                }
                if (Utils.isNull(data.getDetail())) {
                    edDetail.setText("暂无分组描述");
                } else {
                    edDetail.setText(data.getDetail());
                }
                owerEmployeeCode = data.getOwerEmployeeCode();
                teamCode = data.getTeamCode();
                setType();
                tvNum.setVisibility(View.VISIBLE);
                if (!Utils.isNull(data.getTeamCode())) {
                    int size = data.getTeamCode().length();
                    tvNum.setText("分组编号：" + data.getTeamCode().substring(size - 10, size));
                }
                //专门解决1.2.4bug问题  管理员不在群里面的问题
                if (contactAllList.size() > 0) {
                    if (!contactAllList.get(0).getEmployeeCode().equals(data.getOwerEmployeeCode())) {
                        ContactEntity contactEntity = new ContactEntity();
                        contactEntity.setType("1");
                        contactEntity.setEmployeeName(data.getOwerEmployeeName());
                        contactEntity.setEmployeeCode(data.getOwerEmployeeCode());
                        contactEntity.setReviewerFlag("0");
                        contactEntity.setPost(new ShareUtils().getString(LogManagerEditActivity.this, StaticClass.POST, ""));
                        managerCode = new ShareUtils().getString(LogManagerEditActivity.this, StaticClass.EMPLOYEECODE, "");
                        managerName = new ShareUtils().getString(LogManagerEditActivity.this, StaticClass.USER_NICKNAME, "");
                        managerUrl = new ShareUtils().getString(LogManagerEditActivity.this, StaticClass.USER_AVATAR_URL, "");
                        contactEntity.setHeadPhotoThumbUrl(managerUrl);
                        contactAllList.add(0, contactEntity);
                        editData(2);
                    }
                }
                if (data.getOwerEmployeeCode().equals(new ShareUtils().getString(LogManagerEditActivity.this, StaticClass.EMPLOYEECODE, ""))) {
                    isManager = true;
                } else {
                    isManager = false;
                }
                if (type == 0) {
                    //编辑
                    if (isManager) {
                        //管理员  可以转让群 和删除分组
                        if (contactAllList.size() > 15) {
                            contactLittleList.addAll(contactAllList.subList(0, 13));
                            llMore.setVisibility(View.VISIBLE);
                        } else {
                            contactLittleList.addAll(contactAllList);
                            llMore.setVisibility(View.GONE);
                        }
                        tvChange.setVisibility(View.VISIBLE);
                        tvDelete.setVisibility(View.VISIBLE);
                        ContactEntity contactEntity2 = new ContactEntity();
                        contactEntity2.setType("2");
                        contactEntity2.setEmployeeName("2");
                        contactEntity2.setEmployeeCode("2");
                        contactLittleList.add(contactEntity2);
                        ContactEntity contactEntity3 = new ContactEntity();
                        contactEntity3.setType("3");
                        contactEntity3.setEmployeeName("3");
                        contactEntity3.setEmployeeCode("3");
                        contactLittleList.add(contactEntity3);
                        tvReviewer.setVisibility(View.VISIBLE);
                    } else {
                        //非管理员  只能退出当前分组
                        if (contactAllList.size() > 15) {
                            contactLittleList.addAll(contactAllList.subList(0, 14));
                            llMore.setVisibility(View.VISIBLE);
                        } else {
                            contactLittleList.addAll(contactAllList);
                            llMore.setVisibility(View.GONE);
                        }
                        ContactEntity contactEntity2 = new ContactEntity();
                        contactEntity2.setType("2");
                        contactEntity2.setEmployeeName("2");
                        contactEntity2.setEmployeeCode("2");
                        contactLittleList.add(contactEntity2);
                        tvChange.setVisibility(View.GONE);
                        tvDelete.setVisibility(View.VISIBLE);
                        tvDelete.setText("退出分组");
                        edName.setEnabled(false);
                        edDetail.setEnabled(false);
                        ivNameDelete.setVisibility(View.GONE);
                    }
                } else {
                    //预览
                    if (contactAllList.size() > 15) {
                        contactLittleList.addAll(contactAllList.subList(0, 15));
                    } else {
                        contactLittleList.addAll(contactAllList);
                    }
                    tvChange.setVisibility(View.GONE);
                    tvDelete.setVisibility(View.GONE);
                    edName.setEnabled(false);
                    edDetail.setEnabled(false);
                    ivNameDelete.setVisibility(View.GONE);
                }
                adapter.notifyDataSetChanged();

            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });


    }

    private void addData() {
        if (edName == null) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("teamName", edName.getText().toString());
        map.put("detail", edDetail.getText().toString());
        if (choiceType == 0) {
            map.put("reportType", "3");
        } else if (choiceType == 1) {
            map.put("reportType", "0");
        } else if (choiceType == 2) {
            map.put("reportType", "1");
        } else if (choiceType == 3) {
            map.put("reportType", "2");
        }
        String employeeCodes = "";
        for (int i = 0; i < contactLittleList.size() - 2; i++) {
            if (i == 0) {
                employeeCodes = contactLittleList.get(i).getEmployeeCode();
            } else {
                employeeCodes = employeeCodes + "," + contactLittleList.get(i).getEmployeeCode();
            }
        }

        map.put("employeeCodes", employeeCodes);
        String employeeCodeYues = "";
        for (int i = 0; i < codeList.size(); i++) {
            if (i == 0) {
                employeeCodeYues = codeList.get(i);
            } else {
                employeeCodeYues = employeeCodeYues + "," + codeList.get(i);
            }
        }
        map.put("reviewerUser", employeeCodeYues);
        MyHttpRequest.postRequest(Urls.addReportTeam, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {

                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("创建成功");
                        EventBus.getDefault().post(new MyEvent("RefreshLogMangerFragment"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void editData(int editType) {
        //0修改分组 1非管理员退出分组  2解决1.2.4bug 管理员不在分组里面
        if (edName == null) {
            return;
        }
        //修改分组
        Map<String, String> map = new HashMap<>();
        map.put("teamName", edName.getText().toString());
        map.put("detail", edDetail.getText().toString());
        map.put("id", id);
        String employeeCodes = "";
        for (int i = 0; i < contactAllList.size(); i++) {
            if (i == 0) {
                employeeCodes = contactAllList.get(i).getEmployeeCode();
            } else {
                employeeCodes = employeeCodes + "," + contactAllList.get(i).getEmployeeCode();
            }
        }
        map.put("employeeCodes", employeeCodes);
        map.put("teamCode", teamCode);
        map.put("reportType", reportType);
        MyHttpRequest.postRequest(Urls.updateReportTeam, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        if (editType != 2) {
                            if (isEdit) {
                                adapter.notifyDataSetChanged();
                                isEdit = false;
                            }
                            if (editType == 1) {
                                MyToast.show("退出分组成功");
                            } else {
                                MyToast.show("修改成功");
                            }
                            //创建成功
                            EventBus.getDefault().post(new MyEvent("RefreshLogMangerFragment"));
                            finish();
                        }else{
                            EventBus.getDefault().post(new MyEvent("RefreshLogMangerFragment"));
                        }
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void deleteData() {
        //删除分组
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        MyHttpRequest.postRequest(Urls.deleteReportTeamId, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("删除成功");
                        //创建成功
                        EventBus.getDefault().post(new MyEvent("RefreshLogMangerFragment"));
                        finish();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void updateTeamOwen(String code, String name) {
        //修改分组联系人
        Map<String, String> map = new HashMap<>();
        map.put("owerEmployeeCode", code);
        map.put("owerEmployeeName", name);
        map.put("id", id);
        map.put("teamCode", teamCode);
        MyHttpRequest.postRequest(Urls.updateReportTeamOwen, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    dismissLoading();
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        MyToast.show("转让成功");
                        if (tvChange == null) {
                            return;
                        }
                        isManager = false;
                        isEdit = false;
                        tvChange.setVisibility(View.GONE);
                        tvDelete.setVisibility(View.GONE);
                        changeManager(code);
                        EventBus.getDefault().post(new MyEvent("RefreshLogMangerFragment"));
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class MyContactEntityAdapter extends BaseQuickAdapter<ContactEntity, BaseViewHolderEx> {
        private Context context;

        public MyContactEntityAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<ContactEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, ContactEntity item) {

            RelativeLayout rlInit = helper.getView(R.id.rlInit);
            RelativeLayout rlRl = helper.getView(R.id.rlRl);
            LinearLayout llType = helper.getView(R.id.llType);
            TextView tvName = helper.getView(R.id.tvName);
            TextView tvGuan = helper.getView(R.id.tvGuan);
            TextView tvYue = helper.getView(R.id.tvYue);
            ImageView ivInit = helper.getView(R.id.ivInit);
            ImageView ivHead = helper.getView(R.id.ivHead);
            ImageView ivType = helper.getView(R.id.ivType);
            if (helper.getItemPosition() == 0) {
                rlInit.setVisibility(View.GONE);
                rlRl.setVisibility(View.VISIBLE);
                GlideUtils.loadCustomRound(LogManagerEditActivity.this, item.getHeadPhotoThumbUrl(), ivHead, R.drawable.default_user_head, 8);
                tvName.setText(item.getEmployeeName());
                tvName.setVisibility(View.VISIBLE);
                tvGuan.setVisibility(View.VISIBLE);
                if ("1".equals(item.getReviewerFlag())) {
                    tvYue.setVisibility(View.VISIBLE);
                } else {
                    tvYue.setVisibility(View.GONE);
                }
                ivType.setVisibility(View.GONE);
            } else {
                tvGuan.setVisibility(View.GONE);
                if ("2".equals(item.getEmployeeCode())) {
                    //+
                    rlInit.setVisibility(View.VISIBLE);
                    ivInit.setBackgroundResource(R.drawable.icon_add_43);
                    rlRl.setVisibility(View.GONE);
                    tvName.setVisibility(View.INVISIBLE);
                    ivType.setVisibility(View.GONE);
                } else if ("3".equals(item.getEmployeeCode())) {
                    //-
                    rlInit.setVisibility(View.VISIBLE);
                    ivInit.setBackgroundResource(R.drawable.icon_jian_43);
                    rlRl.setVisibility(View.GONE);
                    tvName.setVisibility(View.INVISIBLE);
                    ivType.setVisibility(View.GONE);
                } else {
                    //普通人
                    rlInit.setVisibility(View.GONE);
                    rlRl.setVisibility(View.VISIBLE);
                    GlideUtils.loadCustomRound(LogManagerEditActivity.this, item.getHeadPhotoThumbUrl(), ivHead, R.drawable.default_user_head, 8);
                    tvName.setText(item.getEmployeeName());
                    if ("1".equals(item.getReviewerFlag())) {
                        tvYue.setVisibility(View.VISIBLE);
                    } else {
                        tvYue.setVisibility(View.GONE);
                    }
                    tvName.setVisibility(View.VISIBLE);
                    if (isEdit) {
                        ivType.setVisibility(View.VISIBLE);
                        llType.setVisibility(View.GONE);
                    } else {
                        ivType.setVisibility(View.GONE);
                        llType.setVisibility(View.VISIBLE);
                    }
                }
            }
            ivHead.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Utils.isNull(item.getEmployeeCode())) {
                        return;
                    }
                    Intent intent = new Intent(LogManagerEditActivity.this, PersonalHomeActivity.class);
                    intent.putExtra("employeeCode", item.getEmployeeCode());
                    startActivity(intent);
                }
            });

            ivHead.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (isManager && !isEdit) {
                        updateViewersDialog(item, helper.getItemPosition());
                    }
                    return true;
                }
            });
            ivInit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.getType().equals("2")) {
//                    //默认0是编辑 1创建分组2预览分组
                        MyApp.contactEntityLogList.clear();
                        MyApp.contactEntityLogList.addAll(contactAllList);
                        Intent intent = new Intent(LogManagerEditActivity.this, ContactsLogChoiceActivity.class);
                        intent.putExtra("source", SOURSE + "");
                        intent.putExtra("oldContactNum", contactAllList.size());
                        intent.putExtra("hrName", "已选择分组成员：");
                        startActivity(intent);
                    } else {
                        isEdit = true;
                        adapter.notifyDataSetChanged();
                    }
                }
            });
            ivType.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    contactLittleList.remove(helper.getItemPosition());
                    contactAllList.remove(helper.getItemPosition());
                    adapter.notifyItemRemoved(helper.getItemPosition());
                    adapter.notifyItemRangeChanged(helper.getItemPosition(), contactLittleList.size() - helper.getItemPosition());
                }
            });
        }

    }

    private void updateViewersDialog(ContactEntity contactEntity, int index) {
        String title = "";
        if ("1".equals(contactEntity.getReviewerFlag())) {
            title = "取消该员工为查阅者";
        } else {
            title = "设置该员工为查阅者";
        }
        new android.app.AlertDialog.Builder(this)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (type == 1) {
                            dealCode(contactEntity, index);
                        } else {
                            updateViewers(contactEntity, index);
                        }

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setMessage(title)
                .setTitle("提示")
                .show();
    }

    //创建分组 设置查阅者的逻辑
    private void dealCode(ContactEntity contactEntity, int index) {
        if ("1".equals(contactEntity.getReviewerFlag())) {
            MyToast.show("取消成功");
            contactLittleList.get(index).setReviewerFlag("0");
            for (int i = 0; i < codeList.size(); i++) {
                if (codeList.get(i).equals(contactEntity.getEmployeeCode())) {
                    codeList.remove(i);
                }
            }
        } else {
            MyToast.show("设置成功");
            contactLittleList.get(index).setReviewerFlag("1");
            codeList.add(contactEntity.getEmployeeCode());
        }
        adapter.notifyItemChanged(index);
    }

    private void updateViewers(ContactEntity contactEntity, int index) {
        Map<String, String> map = new HashMap<>();
        map.put("teamCode", teamCode);
        map.put("employeeCode", contactEntity.getEmployeeCode());
        if ("1".equals(contactEntity.getReviewerFlag())) {
            map.put("statusCd", "0");
        } else {
            map.put("statusCd", "1");
        }
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.setReviewer, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if ("1".equals(contactEntity.getReviewerFlag())) {
                    MyToast.show("取消成功");
                    contactLittleList.get(index).setReviewerFlag("0");
                } else {
                    MyToast.show("设置成功");
                    contactLittleList.get(index).setReviewerFlag("1");
                }
                adapter.notifyItemChanged(index);
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getServerData(List<String> orgCodeList, List<String> employeeCodeList) {
        //把选择的部门里面的人全部查出来
        Map<String, Object> map = new HashMap<>();
        map.put("orgCode", JSON.toJSONString(orgCodeList));
        map.put("employeeCode", JSON.toJSONString(employeeCodeList));
        showLoading();
        MyHttpRequest.postRequestJson(Urls.getSelectedEmployee, this, XJson.mapToJObj(map).toString(), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                dismissLoading();
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        List<ContactEntity> serverList = new ArrayList<>();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject2 = jsonArray.getJSONObject(i);
                            ContactEntity contactEntity = new ContactEntity();
                            contactEntity.setEmployeeName(jsonObject2.getString("employeeName"));
                            contactEntity.setEmployeeCode(jsonObject2.getString("employeeCode"));
                            contactEntity.setHeadPhotoThumbUrl(jsonObject2.getString("headPhotoThumbUrl"));
                            contactEntity.setType("1");
                            contactEntity.setEmpNum("0");
                            contactEntity.setReviewerFlag("0");
                            contactEntity.setHalfSelect(false);
                            contactEntity.setSelect(false);
                            serverList.add(contactEntity);
                            for (int j = 0; j < contactAllList.size(); j++) {
                                ContactEntity contactEntity2 = contactAllList.get(j);
                                if (contactEntity2.getEmployeeCode().equals(contactEntity.getEmployeeCode())) {
                                    serverList.remove(serverList.size() - 1);
                                }
                            }
                        }
                        contactAllList.addAll(serverList);
                        setServerData();
                    } else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    dismissLoading();
                    MyToast.show("网络，请稍后重试");
                }
            }
        });
    }

    private void setServerData() {
        if (recyclerView == null) {
            return;
        }
        contactLittleList.clear();
        if (isManager) {
            //管理员  可以转让群 和删除分组
            if (contactAllList.size() > 15) {
                contactLittleList.addAll(contactAllList.subList(0, 13));
                llMore.setVisibility(View.VISIBLE);
            } else {
                contactLittleList.addAll(contactAllList);
                llMore.setVisibility(View.GONE);
            }
            ContactEntity contactEntity2 = new ContactEntity();
            contactEntity2.setType("2");
            contactEntity2.setEmployeeName("2");
            contactEntity2.setEmployeeCode("2");
            contactLittleList.add(contactEntity2);
            ContactEntity contactEntity3 = new ContactEntity();
            contactEntity3.setType("3");
            contactEntity3.setEmployeeName("3");
            contactEntity3.setEmployeeCode("3");
            contactLittleList.add(contactEntity3);
            tvReviewer.setVisibility(View.VISIBLE);
        } else {
            //非管理员  只能退出当前分组
            if (contactAllList.size() > 15) {
                contactLittleList.addAll(contactAllList.subList(0, 14));
                llMore.setVisibility(View.VISIBLE);
            } else {
                contactLittleList.addAll(contactAllList);
                llMore.setVisibility(View.GONE);
            }
            ContactEntity contactEntity2 = new ContactEntity();
            contactEntity2.setType("2");
            contactEntity2.setEmployeeName("2");
            contactEntity2.setEmployeeCode("2");
            contactLittleList.add(contactEntity2);
        }
        adapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("LogChangeManger_code")) {
                updateTeamOwen(map.get("LogChangeManger_code"), map.get("LogChangeManger_name"));
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("ChoiceContacts_Ok_" + SOURSE)) {
                if (MyApp.contactEntityLogList.size() > 0) {
                    List<String> orgCodeList = new ArrayList<>();
                    List<String> employeeCodeList = new ArrayList<>();
                    for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                        ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                        if (!contactEntity.isHalfSelect()) {
                            if (contactEntity.getType().equals("0")) {
                                orgCodeList.add(contactEntity.getEmployeeCode());
                            } else {
                                employeeCodeList.add(contactEntity.getEmployeeCode());
                            }
                        }
                    }
                    if (orgCodeList.size() > 0) {
                        getServerData(orgCodeList, employeeCodeList);
                    } else {
                        //没有组织，
                        List<ContactEntity> acceptList = new ArrayList<>();
                        for (int i = 0; i < MyApp.contactEntityLogList.size(); i++) {
                            ContactEntity contactEntity = MyApp.contactEntityLogList.get(i);
                            if (!contactEntity.isHalfSelect()) {
                                acceptList.add(contactEntity);
                                for (int j = 0; j < contactAllList.size(); j++) {
                                    ContactEntity contactEntity2 = contactAllList.get(j);
                                    if (contactEntity2.getEmployeeCode().equals(contactEntity.getEmployeeCode())) {
                                        acceptList.remove(acceptList.size() - 1);
                                    }
                                }
                            }
                        }
                        contactAllList.addAll(acceptList);
                        setServerData();
                    }

                }
            }
        }
    }

    private void changeManager(String code) {
        //转让群主后不能编辑
        if (ivNameDelete == null) {
            return;
        }
        edName.setEnabled(false);
        edDetail.setEnabled(false);
        ivNameDelete.setVisibility(View.GONE);
        for (int i = 0; i < contactAllList.size(); i++) {
            ContactEntity contactEntity = contactAllList.get(i);
            if (contactEntity.getEmployeeCode().equals(code)) {
                managerCode = contactEntity.getEmployeeCode();
                managerName = contactEntity.getEmployeeName();
                managerUrl = contactEntity.getHeadPhotoThumbUrl();
                contactAllList.remove(i);
                contactAllList.add(0, contactEntity);
                contactLittleList.clear();
                if (contactAllList.size() > 15) {
                    contactLittleList.addAll(contactAllList.subList(0, 14));
                    llMore.setVisibility(View.VISIBLE);
                } else {
                    contactLittleList.addAll(contactAllList);
                    llMore.setVisibility(View.GONE);
                }
                ContactEntity contactEntity2 = new ContactEntity();
                contactEntity2.setType("2");
                contactEntity2.setEmployeeName("2");
                contactEntity2.setEmployeeCode("2");
                contactLittleList.add(contactEntity2);
                adapter.notifyDataSetChanged();
            }
        }
    }

    private List<ContactEntity> removeDuplicate(List<ContactEntity> list) {
        //去重
        Set<ContactEntity> set = new HashSet<ContactEntity>();
        List<ContactEntity> newList = new ArrayList<ContactEntity>();
        for (Iterator<ContactEntity> iter = list.iterator(); iter.hasNext(); ) {
            ContactEntity element = (ContactEntity) iter.next();
            if (set.add(element))
                newList.add(element);
        }
        return newList;
    }

    @OnClick({R.id.common_title_back, R.id.llMore, R.id.common_right_txt, R.id.ivNameDelete, R.id.tvLogChoiceLog, R.id.tvLogChoiceDaily, R.id.tvLogChoiceWeekly, R.id.tvLogChoiceMonthly, R.id.tvChange, R.id.tvDelete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.llMore:
                if (type == 0) {
                    //编辑模式
                    if (isManager) {
                        //管理员
                        contactLittleList.addAll(13, contactAllList.subList(13, contactAllList.size()));
                        adapter.notifyItemRangeChanged(13, contactAllList.size() - 13 + 2);
                    } else {
                        //非管理员
                        contactLittleList.addAll(14, contactAllList.subList(14, contactAllList.size()));
                        adapter.notifyItemRangeChanged(14, contactAllList.size() - 14 + 1);
                    }
                } else {
                    //预览模式
                    int oldNum = contactLittleList.size();
                    contactLittleList.addAll(contactAllList.subList(15, contactAllList.size()));
                    adapter.notifyItemRangeChanged(oldNum, contactAllList.size() - 15);
                }
                llMore.setVisibility(View.GONE);
                break;
            case R.id.common_right_txt:
                if (edName == null) {
                    return;
                }
                if (type == 1) {
                    //新建分组
                    if (Utils.isNull(edName.getText().toString())) {
                        MyToast.show("请编辑分组名称");
                    } else if (Utils.isNull(edDetail.getText().toString())) {
                        MyToast.show("请编辑分组描述");
                    } else {
                        addData();
                    }
                } else {
                    //修改分组
                    if (Utils.isNull(edName.getText().toString())) {
                        MyToast.show("请编辑分组名称");
                    } else if (Utils.isNull(edDetail.getText().toString())) {
                        MyToast.show("请编辑分组描述");
                    } else {
                        editData(0);
                    }
                }
                break;
            case R.id.ivNameDelete:
                if (edName == null) {
                    return;
                }
                edName.setText("");
                break;
            case R.id.tvLogChoiceLog:
                if (type == 1) {
                    choiceType = 0;
                    setType();
                }
                break;
            case R.id.tvLogChoiceDaily:
                if (type == 1) {
                    choiceType = 1;
                    setType();
                }
                break;
            case R.id.tvLogChoiceWeekly:
                if (type == 1) {
                    choiceType = 2;
                    setType();
                }
                break;
            case R.id.tvLogChoiceMonthly:
                if (type == 1) {
                    choiceType = 3;
                    setType();
                }
                break;
            case R.id.tvChange:
                List<ContactEntity> contactEntities = new ArrayList<>();
                contactEntities.addAll(contactAllList);
                Intent intent = new Intent(LogManagerEditActivity.this, LogContactsChangeActivity.class);
                intent.putExtra("dataList", (Serializable) contactEntities);
                startActivity(intent);
                break;
            case R.id.tvDelete:
                if (isManager) {
                    new AlertDialog.Builder(this)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    deleteData();
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setMessage("确定要删除分组么?")
                            .setTitle("提示")
                            .show();
                } else {
                    new AlertDialog.Builder(this)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    int index = -1;
                                    String employeecode = new ShareUtils().getString(LogManagerEditActivity.this, StaticClass.EMPLOYEECODE, "");
                                    for (int i = 0; i < contactAllList.size(); i++) {
                                        if (contactAllList.get(i).getEmployeeCode().equals(employeecode)) {
                                            index = i;
                                        }
                                    }
                                    if (index > -1) {
                                        contactAllList.remove(index);
                                        editData(1);
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            })
                            .setMessage("确定要退出分组么?")
                            .setTitle("提示")
                            .show();
                }

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (edName != null) {
            Utils.hideInputKeyboard(this, edName);
        }
    }
}
